$(function () {
    layui.use(['table',  'form'], function () {
        table = layui.table
        var  $ = layui.$;
        form = layui.form;

        //type1
        $('#type1').attr("disabled", true);
        AjaxGet("/jzweb/jazSignupGroup/list").then(function (response) {
            //设置select
            $('#type1').empty();
            $('#type1').append($('<option>', {
                value: '',
                text: '请选择所属组别'
            }))
            response.data.forEach(item => {
                $('#type1').append($('<option>', {
                    value: item.id,
                    text: item.name
                }))
            })
            $('#type1').attr("disabled", false);
            form.render('select');
        }).catch(function (error) {
            layer.msg(error.msg)
        })
        form.on('select(type1)', function(data){
            var elem = data.elem; // 获得 select 原始 DOM 对象
            var value = data.value; // 获得被选中的值
            $('#type2').attr("disabled", true);
            $('#type2').empty();
            if(value){
                //type2
                $('#type2').attr("disabled", true);
                AjaxGet(`/jzweb/jazSignupItem/list?groupId=${value}`).then(function (response) {
                    $('#type2').empty();
                    $('#type2').append($('<option>', {
                        value: '',
                        text: '请选择参赛项目类型'
                    }))
                    response.data.forEach(item => {
                        $('#type2').append($('<option>', {
                            value: item.id,
                            text: item.name
                        }))
                    })

                    $('#type2').attr("disabled", false);
                    form.render('select');
                    setMyWhere()
                    table.reload('exampleTable', {
                        page: {
                            curr: 1 //重新从第 1 页开始
                        }
                        , where: myWhere
                    });
                }).catch(function (error) {
                    layer.msg(error.msg)
                })
            }else{
                $('#type2').append($('<option>', {
                    value: '',
                    text: '请先选择所属组别'
                }))
            }
            $('#type2').attr("disabled", false);
            form.render('select');

        });

        // 创建渲染实例
        table.render({
            elem: '#exampleTable'
            , id: 'exampleTable'
            , url: '/jzweb/jazSignupTeam/list'
            ,method:'get'
            ,contentType: 'application/x-www-form-urlencoded'
            // ,contentType: 'application/json'
            , cellMinWidth: 80
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                , curr: pages //设定初始在第 5 页
                , groups: 5 //只显示 1 个连续页码
                , limit: 15
                , limits : [15,30,50,100,200]
            }
            , request: {
                pageName: 'curr' //页码的参数名称，默认：page
                , limitName: 'pageSize'
            }
            , where: myWhere
            , defaultToolbar: false
            , loading: false
            , cols:myCols
            , response: {
                statusCode: 0 //重新规定成功的状态码为 200，table 组件默认为 0
            }
            , parseData: function (res) {
                if (res.code != 0) {
                    return false;
                }
                if(Number(res.data.total)>0&&res.data.records.length==0){
                    pages--;
                    if(pages>0) {
                        table.reload('exampleTable', {
                            page: {curr: pages},
                            where: myWhere
                        })
                    }
                }
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            }
            , jump: function (obj, first) {
                //首次不执行
                if (!first) {
                    pages = obj.curr
                }
            }
            , error: function (res, msg) {
                console.log(res, msg)
            }
            , done: function (res) {
                layer.close()
                hindLoading()
            }
        });

        var $ = layui.$, active = {
            reload: function () {
                setMyWhere()
                //执行重载
                table.reload('exampleTable', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , where: myWhere
                });
            }
        };

        /**
         * 搜索事件
         */
        $('.demoTable .layui-btn').on('click', function () {
            var type = $(this).data('type');
            setMyWhere()
            active[type] ? active[type].call(this) : '';
        });

    });


});
let table = null;
let myWhere = {},form =null;

const setMyWhere = () => {
    myWhere = {
        teamName:$('#username').val(),
        groupId:$('#type1').val(),
        itemId:$('#type2').val(),

    }
}
setMyWhere()
let myCols = [[
    {
        field: 'checkbox',
        checkbox: true
    },
        {
            field: 'groupName',
            title: '所属组别',
            align: 'center'
        },
        {
            field: 'name',
            align: 'center',
            title: '队伍名称'
        },
        {
            field: 'createTime',
            align: 'center',
            title: '开始时间',
        },
        {
            field: 'id',
            align: 'center',
            title: '操作',
            templet : function(d) {
                var e = '<a  class="btn btn-primary btn-sm '+look_info+'" href="#" mce_href="#" title="详情" onclick="lookInfo(\''
                    + d.id
                    + '\' )"><i class="fa fa-send"></i></a> ';
                var dao = '<a  class="btn btn-primary btn-sm '+look_daochu+'" href="#" mce_href="#" title="导出" onclick="daochuOne(\''
                    + d.id
                    + '\' )"><i class="fa fa-download"></i></a> ';

                var ss = '<a class="btn btn-success btn-sm '+look_remove+'" href="#" title="删除"  mce_href="#" onclick="remove(\''
                    + d.id
                    + '\')"><i class="fa fa-remove"></i></a>';
                return  e + dao + ss;
            }
        },
    ]]

/**
 * 重置
 */
const dataReset = () => {
    $("#type1").val('')
    $("#type2").val('')
    $("#username").val('')
    form.render('select');
    setMyWhere()
    table.reload('exampleTable', {
        page: {
            curr: 1 //重新从第 1 页开始
        }
        , where: myWhere
    });
}
let pages = 1;

/**
 * 所有的重置表格
 */
function load(){
    layui.use(['table'], ()=>{
        layui.table.reload('exampleTable',{
            where: myWhere
        })
    })
}
const daochuOne=(id)=>{
    var str='?';
    str+=`ids=${id}`
    myDownFiles(`/jzweb/jazSignupTeam/download${str}`)
    layer.close(index);
}
const daochu=()=>{
    var rows = table.checkStatus('exampleTable').data
    layer.confirm(rows.length>0?'确认导出选中的'+rows.length+'条数据吗？':"确认要导出表格数据吗？", {
        btn : [ '确定', '取消' ]
        // 按钮
    }, function(index, layero) {
        console.log('导出==')
        var ids = new Array(),str='?';
        if(rows.length>0){
            $.each(rows, function(i, row) {
                ids[i] = row['id'];
            });
        }
        str+=`ids=${ids}`
        myDownFiles(`/jzweb/jazSignupTeam/download${str}`)
        layer.close(index);
    }, function() {
    })
}

function lookInfo(id){
    sessionStorage.setItem('checkId',id);
    let toIndex=layer.open({
        type: 2,
        title:'队伍详情',
        maxmin: true,
        shadeClose: false,
        area:['800px','500px'],
        content:  `/team/info/${id}`
    });
    layer.full(toIndex);
}
function remove(id) {
    layer.confirm('是否删除此队伍？', {
        btn : [ '确定', '取消' ]
    }, function() {
        $.ajax({
            url : "/jzweb/jazSignupTeam/remove",
            type : "post",
            data : {
                'id' : id
            },
            success : function(r) {
                if (r.code==0) {
                    layer.msg(r.msg);
                    load();
                }else{
                    layer.msg(r.msg);
                }
            }
        });
    })
}